package com.xrz.sxm.base.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.huobao.yunying.utils.Utils;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.utils.ExitUtil;
import com.xrz.sxm.base.utils.ScreenUtil;
import com.xrz.sxm.base.view.NumberProgressBar;

import java.text.DecimalFormat;

public class BaseDialog {

	// 是否确认
	static boolean bIsConfirm;
	// 点击那个按钮
	static int bIsBtn;
	// 编辑框
	static EditText m_edtText;

	private static String input;

	public static ProgressDialog showDialog(Activity mActivity, String msg) {
		ProgressDialog progressDialog = null;
		if ((progressDialog == null) || (!progressDialog.isShowing())) {
			progressDialog = ProgressDialog.show(mActivity, "提示", msg, true);

			// progressDialog.getWindow().setType(
			// WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

			progressDialog
					.setOnKeyListener(new DialogInterface.OnKeyListener() {

						@Override
						public boolean onKey(DialogInterface dialog,
											 int keyCode, KeyEvent event) {
							switch (keyCode) {
								case KeyEvent.KEYCODE_HOME:
									return true;
							}
							return false;
						}
					});
			progressDialog.setCancelable(true);

		}
		return progressDialog;
	}

	public static void cancelDialog(ProgressDialog pro) {
		if (pro != null && pro.isShowing()) {
			pro.cancel();
		}
	}

	private static Dialog dialog;

	private static void createDialog(Context ctx) {
		dialog = new MyDialog(ctx, R.style.dialogdialog);
		dialog.setCanceledOnTouchOutside(false);
		Window window = dialog.getWindow();
		window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
		window.setWindowAnimations(R.style.dialoganimationstyle); // 添加动画
	}

	// /////////////////////////////////////////////下载进度
	private static NumberProgressBar m_NumberProgressBar;
	private static TextView tv_speed, tv_size;
	private static DecimalFormat m_Format;
	private static onProDialogDismissListener m_Listener;

	public static void showProgressDialog(Context ctx,
										  final onProDialogDismissListener listener) {
		m_Listener = listener;
		m_Format = new DecimalFormat("#.00");
		createDialog(ctx);
		View view = LayoutInflater.from(ctx).inflate(
				R.layout.layout_progress_dialog, null);
		m_NumberProgressBar = (NumberProgressBar) view
				.findViewById(R.id.numberProgressbar);
		tv_size = (TextView) view.findViewById(R.id.tv_size);
		tv_speed = (TextView) view.findViewById(R.id.tv_speed);
		Button btn = (Button) view.findViewById(R.id.btn_quxiao);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				listener.onDismiss(true);
				dialog.dismiss();
				dialog = null;
				m_NumberProgressBar = null;
			}
		});
		int width = ScreenUtil.getInstant().getDisWidth(ctx);
		LayoutParams layoutParams = new LayoutParams(width - 60,
				LayoutParams.WRAP_CONTENT);
		dialog.setContentView(view, layoutParams);
		dialog.show();
	}

	public static void setProgressText(long progress, long max) {
		if (m_NumberProgressBar == null) {
			return;
		}
		tv_size.setText(format(progress) + " / " + format(max));
	}

	public static void setSpeed(double speed) {
		tv_speed.setText(format(speed) + "/ s");
	}

	private static String format(double size) {
		if (size > 1024d * 1000d) {
			return m_Format.format(size / 1000d / 1024d) + "M";
		} else if (size < 1000d) {
			return size + "B";
		} else {
			return m_Format.format(size / 1000d) + "KB";
		}
	}

	public static void setProgress(int progress) {
		if (m_NumberProgressBar == null) {
			return;
		}
		m_NumberProgressBar.setProgress(progress);
	}

	public static void diamissProgress(boolean isSuccess) {
		if (m_NumberProgressBar == null) {
			return;
		}
		m_Listener.onDismiss(isSuccess);
		dialog.dismiss();
		dialog = null;
		m_NumberProgressBar = null;
	}

	public interface onProDialogDismissListener {
		void onDismiss(boolean isSuccess);
	}

	// /////////////////////////////////////////////////////下载进度end

	public static String showEditTextDialog(final Context ctx, int currentNum, int kucun, OnDialogSelectListener listener) {
		createDialog(ctx);
		View view = LayoutInflater.from(ctx).inflate(R.layout.layout_edit_dialog,
				null);
		TextView tv_jia = (TextView) view.findViewById(R.id.tv_jia);
		TextView tv_kucun = (TextView) view.findViewById(R.id.tv_kucun);
		tv_kucun.setText("库存剩余"+kucun);
		final EditText edt_number = (EditText) view.findViewById(R.id.edt_number);
		TextView tv_jian = (TextView) view.findViewById(R.id.tv_jian);
		Button btn1 = (Button) view.findViewById(R.id.btn_1);
		Button btn2 = (Button) view.findViewById(R.id.btn_2);
		edt_number.setText(currentNum == 0 ? "" : currentNum + "");
		edt_number.setSelection(currentNum == 0 ? 0 : (currentNum+"").length());
		tv_jia.setOnClickListener(new ClickListener(ctx, currentNum, kucun, edt_number,listener));
		tv_jian.setOnClickListener(new ClickListener(ctx, currentNum, kucun, edt_number,listener));
		btn1.setOnClickListener(new ClickListener(ctx, currentNum, kucun, edt_number,listener));
		btn2.setOnClickListener(new ClickListener(ctx, currentNum, kucun, edt_number,listener));
		edt_number.addTextChangedListener(new EditListener(ctx, currentNum, kucun, edt_number));
		int width = ScreenUtil.getInstant().getDisWidth(ctx);
		LayoutParams layoutParams = new LayoutParams(width - 60,
				LayoutParams.WRAP_CONTENT);
		dialog.setContentView(view, layoutParams);
		dialog.show();
		new Handler().post(new Runnable() {
			@Override
			public void run() {
				Utils.togSoftkeybord(ctx, edt_number, false);
			}
		});
		return input;
	}


	private static class EditListener implements TextWatcher {
		private Context ctx;
		private int currentNum;
		private int kucun;
		private EditText edt_number;

		public EditListener(Context ctx, int currentNum, int kucun, EditText edt_number) {
			this.ctx = ctx;
			this.currentNum = currentNum;
			this.kucun = kucun;
			this.edt_number = edt_number;
		}

		@Override
		public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

		}

		@Override
		public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
			Editable editable = edt_number.getText();
			if (editable == null) return;
			if (TextUtils.isEmpty(editable.toString())) return;
			if(editable.toString().equals("0")){
				Toast.makeText(ctx, "非法请求", Toast.LENGTH_SHORT).show();
				edt_number.setText("");
				return;
			}

//			int len = editable.length();
			int text = Integer.parseInt(editable.toString().trim());
//			int maxLen = String.valueOf(kucun).length() == len ? len-1 : String.valueOf(kucun).length();
//
			if (text > kucun) {
				edt_number.setText(String.valueOf(kucun));
				edt_number.setSelection(edt_number.getText().length());
				Toast.makeText(ctx, "输入数量超出库存", Toast.LENGTH_SHORT).show();
//				int selEndIndex = Selection.getSelectionEnd(editable);
//				String str = editable.toString();
//				//截取新字符串
//				String newStr = str.substring(0, maxLen);
//				edt_number.setText(newStr);
//				editable = edt_number.getText();
//
//				//新字符串的长度
//				int newLen = editable.length();
//				//旧光标位置超过字符串长度
//				if (selEndIndex > newLen) {
//					selEndIndex = editable.length();
//				}
//				//设置新光标所在的位置
//				Selection.setSelection(editable, selEndIndex);

			} else {
				currentNum = text;
			}
		}

		@Override
		public void afterTextChanged(Editable editable) {

		}
	}


	private static class ClickListener implements OnClickListener {
		private Context ctx;
		private int currentNum;
		private int kucun;
		private EditText edt_number;
		private OnDialogSelectListener listener;

		public ClickListener(Context ctx, int currentNum, int kucun, EditText edt_number,OnDialogSelectListener listener) {
			this.ctx = ctx;
			this.currentNum = currentNum;
			this.kucun = kucun;
			this.edt_number = edt_number;
			this.listener = listener;
		}

		@Override
		public void onClick(View view) {
			switch (view.getId()) {
				case R.id.tv_jia:
					if (currentNum < kucun) {
						currentNum++;
					}
					edt_number.setText(currentNum + "");
					break;
				case R.id.tv_jian:
					if (currentNum > 0) {
						currentNum--;
					}
					edt_number.setText(currentNum + "");
					break;
				case R.id.btn_1:
					input = null;
					try {
						Utils.togSoftkeybord(ctx, edt_number, true);
						dialog.dismiss();
						dialog = null;
					} catch (Exception e) {
					}
					break;
				case R.id.btn_2:
					input = edt_number.getText().toString().trim();
					if (TextUtils.isEmpty(input)) {
						input = null;
						Toast.makeText(ctx, "请输入数量", Toast.LENGTH_SHORT).show();
						return;
					}
					try {
						Utils.togSoftkeybord(ctx, edt_number, true);
						dialog.dismiss();
						dialog = null;
						listener.onSelect(input);
					} catch (Exception e) {
					}
					break;
			}
		}
	}

	public static void showPermissionDialog(final Activity ctx,String msg,final String permission,final int requestCode, final OnDialogSelectListener listener){
		if(dialog != null && dialog.isShowing())return;
			createDialog(ctx);
			View view = LayoutInflater.from(ctx).inflate(R.layout.layout_dialog,
					null);
			TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
			tv_title.setText("系统提示");
			final EditText tv_content = (EditText) view.findViewById(R.id.tv_content);
			tv_content.setEnabled(false);
			tv_content.setText(msg);
			Button btn1 = (Button) view.findViewById(R.id.btn_1);
			Button btn2 = (Button) view.findViewById(R.id.btn_2);
			Button midbtn = (Button) view.findViewById(R.id.btn_3);
		btn1.setText("退出");
		btn2.setText("去允许");
			btn1.setVisibility(View.VISIBLE);
			btn2.setVisibility(View.VISIBLE);
			midbtn.setVisibility(View.GONE);
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				ExitUtil.getInstant().exitApp(ctx);
			}
		});
		btn2.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					String [] permissions = new String[]{permission};
					if(dialog != null && dialog.isShowing()){
						dialog.dismiss();
						dialog = null;
					}
					ActivityCompat.requestPermissions(ctx, permissions, requestCode);
					if(listener != null)
					listener.onSelect("");
				}
			});
			int width = ScreenUtil.getInstant().getDisWidth(ctx);
			LayoutParams layoutParams = new LayoutParams(width - 60,
					LayoutParams.WRAP_CONTENT);
		try{
			dialog.setContentView(view, layoutParams);
			dialog.show();
		}catch(Exception e){}

	}

	public static void showDialog(final Context ctx, String title, String content,
								  String leftBtnText, String rightBtnText, String midBtnText,
								  final int num, final boolean isEdit, final OnDialogSelectListener listener) {

		createDialog(ctx);
		View view = LayoutInflater.from(ctx).inflate(R.layout.layout_dialog,
				null);
		TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
		final EditText tv_content = (EditText) view.findViewById(R.id.tv_content);
		if (isEdit) {
			tv_content.setMinHeight(20);
			tv_content.setGravity(Gravity.TOP);
		}
		tv_content.setEnabled(isEdit);
		Button btn1 = (Button) view.findViewById(R.id.btn_1);
		Button btn2 = (Button) view.findViewById(R.id.btn_2);
		Button midbtn = (Button) view.findViewById(R.id.btn_3);
		btn1.setText(leftBtnText);
		btn2.setText(rightBtnText);
		midbtn.setText(midBtnText);
		LayoutParams lp1 = (LayoutParams) btn1
				.getLayoutParams();
		LayoutParams lp2 = (LayoutParams) midbtn
				.getLayoutParams();
		switch (num) {
			case 1:
				btn2.setVisibility(View.GONE);
				midbtn.setVisibility(View.GONE);
				break;
			case 2:
				btn2.setVisibility(View.VISIBLE);
				midbtn.setVisibility(View.GONE);
				lp1.rightMargin = 1;
				break;
			case 3:
				btn2.setVisibility(View.VISIBLE);
				midbtn.setVisibility(view.VISIBLE);
				lp1.rightMargin = 1;
				lp2.rightMargin = 1;
				break;
		}
		if (title == null) {
			tv_title.setVisibility(View.GONE);
		} else {
			tv_title.setText(title);
		}
		tv_content.setText(content);
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				input = tv_content.getText().toString().trim();
				if (isEdit && input.equals("")) {
					Toast.makeText(ctx, "请输入内容", Toast.LENGTH_SHORT).show();
					return;
				}
				if (isEdit && Integer.parseInt(input) > m_kucun) {
					Toast.makeText(ctx, "数量超过库存！", Toast.LENGTH_SHORT).show();
					return;
				}
				dialog.dismiss();
				dialog = null;
				if (num == 2) {
					bIsConfirm = true;
					listener.onSelect("true");
				}


				if (num == 3) {
					bIsBtn = 1;
				}
			}
		});
		btn2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog.dismiss();
				dialog = null;
				if (num == 2){
					bIsConfirm = false;
					listener.onSelect("false");
				}
				if (num == 3) {
					bIsBtn = 2;
				}
			}
		});
		midbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				dialog = null;
				if (num == 3) {
					bIsBtn = 0;
				}
			}
		});
		int width = ScreenUtil.getInstant().getDisWidth(ctx);
		LayoutParams layoutParams = new LayoutParams(width - 60,
				LayoutParams.WRAP_CONTENT);
		dialog.setContentView(view, layoutParams);
		dialog.show();
	}

	public interface OnDialogSelectListener {
		void onSelect(String input);
	}

	//库存
	private static int m_kucun = 0;


	public static void showAlert(String message, Context context) {
		showDialog(context, "系统提示", message, "确定", "", "", 1, false, null);
	}

	public static void TBox(String message, Context context, OnDialogSelectListener listener) {
		showDialog(context, "系统提示", message, "确定", "取消", "", 2, false,listener);
	}

}
